package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.JsonResult;
import com.ruoyi.web.controller.tool.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;

/**
 * 专家去世确认Controller
 * 
 * @author ruoyi
 * @date 2023-03-30
 */
@Controller
@RequestMapping("/system/zhuanjiaqushiqueren")
public class ZhuanjiaQushiquerenController extends BaseController
{
    //获取配置中的userfilepath的配置数据
    //private String userfilepath = RuoYiConfig.getUploadPath();
    private String userfilepath = "D:/userfiles/zjtt/qushiqueren";

    private String prefix = "system/zhuanjiaqushiqueren";

    @Autowired
    private IZhuanjiaQushiquerenService zhuanjiaQushiquerenService;

    @Autowired
    private IZhuanjiaQushiquerenPiciService zhuanjiaQushiquerenPiciService;

    @Autowired
    private IDeptZhuanjiaService deptZhuanjiaService;

    @Autowired
    IDeptidOlddeptidService olddeptidService;

    @Autowired
    ISysDictDataService sysDictDataService;

    @RequiresPermissions("system:zhuanjiaqushiqueren:view")
    @GetMapping()
    public String zhuanjiaqushiqueren()
    {
        return prefix + "/zhuanjiaqushiqueren";
    }

    @GetMapping("/qushiquerenRenyuanlist")
    public String qushiquerenRenyuanlist(String deptid,ModelMap mmap)
    {
        mmap.put("deptid",deptid);
        return prefix + "/qushiquerenRenyuanlist";
    }

    @GetMapping("/qushiquerenDeptlist")
    public String qushiquerenDeptlist(String deptid,ModelMap mmap)
    {
        mmap.put("deptid",deptid);
        return prefix + "/qushiquerenDeptlist";
    }

    @GetMapping("/customlist")
    public String customlist()
    {
        return prefix + "/customlist";
    }

    //去世确认管理列表
    @GetMapping("/qushiquerenlist")
    public String qushiquerenlist()
    {
        return prefix + "/qushiquerenlist";
    }

    //下级单位去世专家待核查
    @GetMapping("/xiajidanweiqushi")
    public String xiajidanweiqushi()
    {
        return   "system/xiajidanweiqushi/customlist";
    }

    @GetMapping("/qushiquerenmanage")
    public String qushiquerenmanage(@RequestParam("piciid") String ppPiciId,ModelMap ppMap)
    {
        ppMap.put("piciid",ppPiciId);
        return  prefix+"/qushiquerenmanage";
    }
    /**
     * 查询专家去世确认列表
     */
    //@RequiresPermissions("system:zhuanjiaqushiqueren:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZhuanjiaQushiqueren zhuanjiaQushiqueren)
    {
        startPage();
        List<ZhuanjiaQushiqueren> list = zhuanjiaQushiquerenService.selectZhuanjiaQushiquerenList(zhuanjiaQushiqueren);
        return getDataTable(list);
    }

    /**
     * 导出专家去世确认列表
     */
    @RequiresPermissions("system:zhuanjiaqushiqueren:export")
    @Log(title = "专家去世确认", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZhuanjiaQushiqueren zhuanjiaQushiqueren)
    {
        List<ZhuanjiaQushiqueren> list = zhuanjiaQushiquerenService.selectZhuanjiaQushiquerenList(zhuanjiaQushiqueren);
        ExcelUtil<ZhuanjiaQushiqueren> util = new ExcelUtil<ZhuanjiaQushiqueren>(ZhuanjiaQushiqueren.class);
        return util.exportExcel(list, "专家去世确认数据");
    }

    /**
     * 新增专家去世确认
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存专家去世确认
     */
    @RequiresPermissions("system:zhuanjiaqushiqueren:add")
    @Log(title = "专家去世确认", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZhuanjiaQushiqueren zhuanjiaQushiqueren)
    {
        return toAjax(zhuanjiaQushiquerenService.insertZhuanjiaQushiqueren(zhuanjiaQushiqueren));
    }

    /**
     * 修改专家去世确认
     */
    @RequiresPermissions("system:zhuanjiaqushiqueren:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZhuanjiaQushiqueren zhuanjiaQushiqueren = zhuanjiaQushiquerenService.selectZhuanjiaQushiquerenById(id);
        mmap.put("zhuanjiaQushiqueren", zhuanjiaQushiqueren);
        return prefix + "/edit";
    }

    /**
     * 修改保存专家去世确认
     */
    //@RequiresPermissions("system:zhuanjiaqushiqueren:edit")
    @Log(title = "专家去世确认", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZhuanjiaQushiqueren zhuanjiaQushiqueren)
    {
        return toAjax(zhuanjiaQushiquerenService.updateZhuanjiaQushiqueren(zhuanjiaQushiqueren));
    }

    /**
     * 修改保存专家去世确认
     */
    //@RequiresPermissions("system:zhuanjiaqushiqueren:edit")
    @Log(title = "专家去世确认", businessType = BusinessType.UPDATE)
    @PostMapping("/editQushi")
    @ResponseBody
    public AjaxResult editQushi(ZhuanjiaQushiqueren zhuanjiaQushiqueren)
    {
        ZhuanjiaQushiqueren z = zhuanjiaQushiquerenService.selectZhuanjiaQushiquerenById(zhuanjiaQushiqueren.getId());
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datef = sdf.format(d);
        String biandong = sysDictDataService.selectDictLabel("sys_zhuanjiazhuangtai",zhuanjiaQushiqueren.getChulijieguo());
        String str = z.getGongzuodanwei()+"于"+datef+"提交 "+z.getXingming()+" \""+biandong+"\"变动申报";

        zhuanjiaQushiqueren.setChuliriqi(d);
        zhuanjiaQushiqueren.setChulijieguo(str);
        return toAjax(zhuanjiaQushiquerenService.updateZhuanjiaQushiqueren(zhuanjiaQushiqueren));
    }


    /**
     * 删除专家去世确认
     */
    @RequiresPermissions("system:zhuanjiaqushiqueren:remove")
    @Log(title = "专家去世确认", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zhuanjiaQushiquerenService.deleteZhuanjiaQushiquerenByIds(ids));
    }

    /**
     * 专家变动详情custom列表
     */
    @PostMapping("/customlist")
    @ResponseBody
    public JsonResult<?> customlist(@RequestParam("deptid")String ppDeptId,
                                    @RequestParam("zhuanjiaxingming")String ppXingming,
                                    @RequestParam("suoshudanwei")String ppSuoshudanwei,
                                    @RequestParam("shenfenzhenghao")String ppShenfenzhenghao,
                                    @RequestParam("siwangbiaoji")int ppSiwangbiaoji,
                                    @RequestParam("shifouchuli")int ppShifouchuli,
                                    @RequestParam("pageindex") int ppPageIndex,
                                    @RequestParam("pagesize") int ppPageSize)
    {
        try{
            if (ppDeptId.equals(RuoYiConfig.getZjzxdeptid())){
                ppDeptId = "";
            }

            List<Map<String,Object>> list = zhuanjiaQushiquerenService.findCustomList(ppDeptId,ppXingming,ppSuoshudanwei,ppShenfenzhenghao,ppSiwangbiaoji,ppShifouchuli,ppPageIndex,ppPageSize);
            int mmCount = zhuanjiaQushiquerenService.countCustomList(ppDeptId,ppXingming,ppSuoshudanwei,ppShenfenzhenghao,ppSiwangbiaoji,ppShifouchuli);

            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

    /**
     * 下级单位去世待核查列表
     */
    @PostMapping("/xiajidanweiqushilist")
    @ResponseBody
    public JsonResult<?> xiajidanweiqushilist(@RequestParam("yijidanweiid")String ppDeptId,
                                    @RequestParam("zhuanjiaxingming")String ppXingming,
                                    @RequestParam("suoshudanwei")String ppSuoshudanwei,
                                    @RequestParam("shenfenzhenghao")String ppShenfenzhenghao,
                                    @RequestParam("siwangbiaoji")String ppSiwangbiaoji,
                                    @RequestParam("shifouchuli")int ppShifouchuli,
                                    @RequestParam("pageindex") int ppPageIndex,
                                    @RequestParam("pagesize") int ppPageSize)
    {
        try{

            ppDeptId = olddeptidService.DeptIdToOldDeptId(ppDeptId);
            List<Map<String,Object>> list = zhuanjiaQushiquerenService.xiajidanweiqushilist(ppDeptId,ppXingming,ppSuoshudanwei,ppShenfenzhenghao,ppSiwangbiaoji,ppShifouchuli,ppPageIndex,ppPageSize);
            int mmCount = zhuanjiaQushiquerenService.countxiajidanweiqushilist(ppDeptId,ppXingming,ppSuoshudanwei,ppShenfenzhenghao,ppSiwangbiaoji,ppShifouchuli);

            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

    // 解析上传的EXCEL文件
    @SuppressWarnings("resource")
    @RequestMapping("get_value")
    @ResponseBody
    public JsonResult<?> get_value(
            @RequestParam("fileurl") String mmFileUrl,
            HttpServletRequest request
    ){
        try {
            //取出文档存放的根目录，并去除文件最后的斜杠
            if(userfilepath.endsWith("/")){
                userfilepath  = userfilepath.substring(0, userfilepath.length()-1);
            }

            String url = userfilepath+mmFileUrl;
            Workbook book = null;

            File f = new File(url);
            InputStream in = new FileInputStream(f);

            String prefix = url.substring(url.lastIndexOf(".")+1);
            if(prefix.equals("xls")) {
                book = new HSSFWorkbook(in);
            }else if(prefix.equals("xlsx")) {
                book = new XSSFWorkbook(in);
            }else {
                return JsonResult.getErrorResult("请上传xls或xlsx类型的文件！");
            }

            Sheet sheet = book.getSheetAt(0);
            int column= sheet.getRow(0).getPhysicalNumberOfCells();
            int rows = sheet.getPhysicalNumberOfRows();

            List<Map<String,Object>> mmReturnList = new ArrayList<Map<String,Object>>();

            for (int i = 1; i < rows ; i++) { //行
                Map<String,Object> mmMap = new HashMap<String,Object>();
                mmMap.put("专家ID", getCellFormatValue(sheet.getRow(i).getCell(0)));
                mmMap.put("姓名", getCellFormatValue(sheet.getRow(i).getCell(1)));
                mmMap.put("单位代码", getCellFormatValue(sheet.getRow(i).getCell(2)));
                mmMap.put("所属单位", getCellFormatValue(sheet.getRow(i).getCell(3)));
                mmMap.put("工作单位", getCellFormatValue(sheet.getRow(i).getCell(4)));
                mmMap.put("身份证号", getCellFormatValue(sheet.getRow(i).getCell(5)));
                mmMap.put("死亡标识", getCellFormatValue(sheet.getRow(i).getCell(6)));
                mmMap.put("死亡日期", getCellFormatValue(sheet.getRow(i).getCell(7)));
                mmMap.put("备注", getCellFormatValue(sheet.getRow(i).getCell(8)));
                mmReturnList.add(mmMap);
            }
            in.close();
            return JsonResult.getSuccessResult(mmReturnList);
        } catch (Exception e) {
            logger.error("get_value: "+e.getMessage());
            return JsonResult.getErrorResult("获取上传文件中的数据失败！");
        }
    }

    // 导入高校名单
    @RequestMapping("import")
    @ResponseBody
    public JsonResult<?> importvalue(
            @RequestParam("piciid") String ppPiciId,
            @RequestParam("zhuanjiaid") String ppZhuanjiaId,
            @RequestParam("xingming") String ppXingming,
            @RequestParam("jigoudaima") String ppJigoudaima,
            @RequestParam("suoshudanwei") String ppSuoshudanwei,
            @RequestParam("gongzuodanwei") String ppGongzuodanwei,
            @RequestParam("shenfenzhenghao") String ppShenfenzhenghao,
            @RequestParam("siwangbiaoji") String ppSiwangbiaoji,
            @RequestParam("siwangriqi") String ppSiwangriqi,
            @RequestParam("beizhu") String ppBeizhu,
            HttpServletRequest request
    ){
        try {
            //
            ZhuanjiaQushiqueren mmTemp = new ZhuanjiaQushiqueren();
            mmTemp.setZhuanjiaid(ppZhuanjiaId);
            mmTemp.setShifouchuli((long)0);
            List<ZhuanjiaQushiqueren> mmTempList = zhuanjiaQushiquerenService.selectZhuanjiaQushiquerenList(mmTemp);
            if(mmTempList.size()>0) {
                return JsonResult.getErrorResult("专家"+ppXingming+"已有未处理的核查信息！请检查修改后重新导入该数据！");
            }else {

                ZhuanjiaQushiqueren mmZhuanjiaQushiqueren = new ZhuanjiaQushiqueren();
                mmZhuanjiaQushiqueren.setId(UUID.randomUUID().toString());
                mmZhuanjiaQushiqueren.setZhuanjiaid(ppZhuanjiaId);
                mmZhuanjiaQushiqueren.setXingming(ppXingming);

                DeptZhuanjia mmDeptZhuanjia = deptZhuanjiaService.findByZhuanjiaId(ppZhuanjiaId);
                if (mmDeptZhuanjia==null){
                    return JsonResult.getErrorResult("查询专家出错！");
                }

                mmZhuanjiaQushiqueren.setPiciid(ppPiciId);
                mmZhuanjiaQushiqueren.setJigoudaima(mmDeptZhuanjia.getDeptid());
                mmZhuanjiaQushiqueren.setSuoshudanwei(mmDeptZhuanjia.getDanweimingcheng());
                mmZhuanjiaQushiqueren.setYijidanweiid(ppJigoudaima);
                mmZhuanjiaQushiqueren.setYijidanweimingcheng(ppSuoshudanwei);
                mmZhuanjiaQushiqueren.setGongzuodanwei(ppGongzuodanwei);
                mmZhuanjiaQushiqueren.setShenfenzhenghao(ppShenfenzhenghao);
                mmZhuanjiaQushiqueren.setSiwangbiaoji(ppSiwangbiaoji);

                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                Date mmSiwangriqi = ft.parse(ppSiwangriqi);

                mmZhuanjiaQushiqueren.setSiwangriqi(mmSiwangriqi);
                mmZhuanjiaQushiqueren.setBeizhu(ppBeizhu);
                mmZhuanjiaQushiqueren.setAddtime(new Date());
                mmZhuanjiaQushiqueren.setShifouchuli((long)0);
                mmZhuanjiaQushiqueren.setIsvalid((long)1);

                ZhuanjiaBiandongDetail mmBiandong = new ZhuanjiaBiandongDetail();
                String mmBiandongId = UUID.randomUUID().toString();
                mmBiandong.setId(mmBiandongId);
                mmBiandong.setDeptid(olddeptidService.OldDeptIdToDeptId(mmDeptZhuanjia.getDeptid()));
                mmBiandong.setZhuanjiaid(ppZhuanjiaId);
                mmBiandong.setZhuanjiamingcheng(ppXingming);
                mmBiandong.setBiandongleixing("5");//5：去世
                mmBiandong.setBiandongriqi(mmSiwangriqi);
                mmBiandong.setIsused((long)0);
                mmBiandong.setIsvalid((long)1);
                //添加时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                mmBiandong.setBeizhu2(sdf.format(new Date()));

                mmZhuanjiaQushiqueren.setBiandongid(mmBiandongId);

                ZhuanjiaQushiquerenPici mmPici = zhuanjiaQushiquerenPiciService.selectZhuanjiaQushiquerenPiciById(ppPiciId);
                if (mmPici==null){
                    return JsonResult.getErrorResult("该批次不存在");
                }
                mmPici.setRenshu(mmPici.getRenshu()+1);
                mmPici.setWeihecha(mmPici.getWeihecha()+1);

//                if(zhuanjiaQushiquerenService.insertZhuanjiaQushiqueren(mmZhuanjiaQushiqueren)!=1) {
//                    return JsonResult.getErrorResult("导入错误！");
//                }

                boolean add = zhuanjiaQushiquerenService.addZhuanjiaQushiAndBiandong(mmZhuanjiaQushiqueren,mmBiandong,mmPici);

                return add==true?JsonResult.getSuccessResult("添加成功"):JsonResult.getErrorResult("添加失败");
            }

        } catch (Exception e) {
            logger.error("ZhuanjiaQushiquerenController -> importvalue: "+e.getMessage());
            return JsonResult.getErrorResult("导入专家去世确认名单失败！");
        }
    }

    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字
                        cell.setCellType(1);
                        // 取得当前Cell的数值
                        //cellvalue = String.valueOf(cell.getNumericCellValue());
                        cellvalue=cell.getStringCellValue();
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    @PostMapping("/qushiquerenmanagelist")
    @ResponseBody
    public JsonResult<?> qushiquerenmanagelist(@RequestParam("piciid") String piciid,String danweimingcheng,String danweicengji,
                                               String zhuanjiaxingming,String gongzuodanwei,String shifoubiandong,
                                               String shifouchuli,String chuliriqi,int pageindex,int pagesize)
    {

        try{
            List<Map<String,Object>> list = zhuanjiaQushiquerenService.qushiListBypiciid(piciid,danweimingcheng, danweicengji,
                     zhuanjiaxingming, gongzuodanwei, shifoubiandong,
                     shifouchuli, chuliriqi, pageindex, pagesize);
            int mmCount = zhuanjiaQushiquerenService.countqushiListBypiciid(piciid,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei, shifoubiandong,
                    shifouchuli, chuliriqi);

            PageInfo mmPageInfo = new PageInfo(pageindex, pagesize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

    @PostMapping("/qushilist")
    @ResponseBody
    public JsonResult<?> qushilist(String jigoudaima,String danweimingcheng,String danweicengji,
                                               String zhuanjiaxingming,String gongzuodanwei,String shifoubiandong,
                                               String shifouchuli,String chuliriqi,int pageindex,int pagesize)
    {

        try{
            List<Map<String,Object>> list = zhuanjiaQushiquerenService.qushiList(jigoudaima,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei, shifoubiandong,
                    shifouchuli, chuliriqi, pageindex, pagesize);
            int mmCount = zhuanjiaQushiquerenService.countqushiList(jigoudaima,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei, shifoubiandong,
                    shifouchuli, chuliriqi);

            PageInfo mmPageInfo = new PageInfo(pageindex, pagesize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }
}
